package com.ycsj.goldmedalnewconcept;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.flyco.animation.BaseAnimatorSet;
import com.flyco.dialog.listener.OnBtnLeftClickL;
import com.flyco.dialog.listener.OnBtnRightClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.ycsj.goldmedalnewconcept.activity.PhotoActivity;
import com.ycsj.goldmedalnewconcept.activity.SOSOLocationActivity;
import com.ycsj.goldmedalnewconcept.constant.ConfigConstant;
import com.ycsj.goldmedalnewconcept.fragment.AddressListFragment;
import com.ycsj.goldmedalnewconcept.fragment.FriendsFragment;
import com.ycsj.goldmedalnewconcept.fragment.HelperFragment;
import com.ycsj.goldmedalnewconcept.fragment.MsgFragment;
import com.ycsj.goldmedalnewconcept.fragment.NewManageFragment;
import com.ycsj.goldmedalnewconcept.picture.PhotoInputProvider;
import com.ycsj.goldmedalnewconcept.ui.TitleColorSegmentView;
import com.ycsj.goldmedalnewconcept.ui.TitleColorSegmentView.OnSegmentSelectedListener;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.utils.SPUtils;

import java.util.Timer;
import java.util.TimerTask;

import io.rong.imkit.RongContext;
import io.rong.imkit.RongIM;
import io.rong.imkit.RongIM.LocationProvider;
import io.rong.imkit.model.UIConversation;
import io.rong.imkit.widget.provider.CameraInputProvider;
import io.rong.imkit.widget.provider.InputProvider;
import io.rong.imkit.widget.provider.LocationInputProvider;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Conversation.ConversationType;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.UserInfo;
import io.rong.message.ImageMessage;
import io.rong.message.LocationMessage;

//首页
public class MainActivity extends FragmentActivity implements OnClickListener {

    private Fragment[] fragments;
    public MsgFragment msgfragment;
    private AddressListFragment addressListFragment;
    private String UserType;

    private FriendsFragment friendsfragment;
    private NewManageFragment managefragment;
    private HelperFragment helperfragment;
    private ImageView[] imagebuttons;
    private TextView[] textviews;
    private TextView txt_title;
    private TextView tv_manage;
    private ImageView img_right;
    private ImageView iv_msg;
    private ImageView iv_friends;
    private ImageView iv_manage;
    private ImageView iv_helper;
    private int index;
    private int currentTabIndex;
    private String role;
    private TextView mUnreadNumView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        role = SPUtil.getString(this, "role", "");// 获取账号角色类型

        findViewById();
        initViews();
        initTabView();
        setOnListener();
        DemoContext.init(this);
        initIm();
        if ("2".equals(role)) {
            tv_manage.setText("教学管理");
        } else if ("1".equals(role)) {
            tv_manage.setText("宝贝课程");
        } else if ("3".equals(role)) {
            txt_title.setText("");
        }
    }

    private void initTabView() {

        addressListFragment = new AddressListFragment();
        msgfragment = new MsgFragment(); // 消息
        friendsfragment = new FriendsFragment(); // 圈子
        // friendsfragment = new AlreadyHuodongFragment(); // 活动
        // managefragment = new ManageFragment(); //管理
        managefragment = new NewManageFragment(); // 管理
        helperfragment = new HelperFragment(); // 助手

        fragments = new Fragment[]{msgfragment, friendsfragment,
                managefragment, helperfragment, addressListFragment};
        imagebuttons = new ImageView[4];
        imagebuttons[0] = (ImageView) findViewById(R.id.iv_msg);
        imagebuttons[1] = (ImageView) findViewById(R.id.iv_friends);
        imagebuttons[2] = (ImageView) findViewById(R.id.iv_manage);
        imagebuttons[3] = (ImageView) findViewById(R.id.iv_helper);

        imagebuttons[0].setSelected(true);

        textviews = new TextView[4];
        textviews[0] = (TextView) findViewById(R.id.tv_msg);
        textviews[1] = (TextView) findViewById(R.id.tv_friends);
        textviews[2] = (TextView) findViewById(R.id.tv_manage);
        textviews[3] = (TextView) findViewById(R.id.tv_helper);
        textviews[0].setTextColor(0xFF33B8F3);

        getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, msgfragment)
                .add(R.id.fragment_container, addressListFragment)
                .add(R.id.fragment_container, friendsfragment)
                .add(R.id.fragment_container, managefragment)
                .add(R.id.fragment_container, helperfragment)
                .hide(friendsfragment).hide(managefragment)
                .hide(helperfragment).hide(addressListFragment)
                .show(msgfragment).commit();
    }

    public void onTabClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_msg:
                img_right.setVisibility(View.VISIBLE);
                index = 0;
                Log.e("test", "index = 0");
                if (msgfragment != null) {
                    // msgfragment.refresh();
                }
                // 显示标题按钮
                txt_title.setText("");

                sv_title.setVisibility(View.VISIBLE);
                if (!sv_title.isUnlockSelected()) {
                    index = 4;
                    Log.e("test", "index ==== 4");
                }

                break;
            case R.id.rl_friends:
                index = 1;
                txt_title.setText("圈子");
                img_right.setVisibility(View.VISIBLE);
                // img_right.setImageResource(R.drawable);
                sv_title.setVisibility(View.GONE);

                break;
            case R.id.rl_manage:
                index = 2;

                if ("2".equals(role)) {
                    txt_title.setText("教学管理");
                } else if ("1".equals(role)) {
                    txt_title.setText("宝贝课程");
                } else {
                    txt_title.setText("管理");
                }
                sv_title.setVisibility(View.GONE);

                break;
            case R.id.rl_helper:
                index = 3;
                txt_title.setText("个人助手");
                sv_title.setVisibility(View.GONE);
                break;
        }

        Log.e("test", "currentTabIndex ==== " + currentTabIndex);
        if (currentTabIndex != index) {
            FragmentTransaction trx = getSupportFragmentManager()
                    .beginTransaction();
            trx.hide(fragments[currentTabIndex]);
            if (!fragments[index].isAdded()) {
                trx.add(R.id.fragment_container, fragments[index]);
            }
            if (currentTabIndex == 0 && index != 0) {
                trx.hide(fragments[currentTabIndex]);
            }
            trx.show(fragments[index]).commit();
        }

        imagebuttons[currentTabIndex % 4].setSelected(false);
        // 把当前tab设为选中状态״̬
        imagebuttons[index % 4].setSelected(true);
        textviews[currentTabIndex % 4].setTextColor(0xff9A9A9A);
        textviews[index % 4].setTextColor(0xFF33B8F3);
        currentTabIndex = index;
        Log.e("test", "currentTabIndex = " + currentTabIndex);

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void findViewById() {
        txt_title = (TextView) findViewById(R.id.txt_title);
        img_right = (ImageView) findViewById(R.id.img_right);
        tv_manage = (TextView) findViewById(R.id.tv_manage);
        sv_title = (TitleColorSegmentView) findViewById(R.id.sv_title);
    }

    private void initViews() {
        mUnreadNumView = (TextView) findViewById(R.id.de_num);
        img_right.setVisibility(View.VISIBLE);
        // img_right.setImageResource(R.drawable.);
        sv_title.settext("消息", "通讯录");
        sv_title.setOnSegmentSelectedListener(listener);
        if ((!sv_title.isUnlockSelected())) {
            Log.e("test", "index = 4");
            index = 4;
            currentTabIndex = index;
        } else {
            Log.e("test", "index = 0");
            index = 0;
            currentTabIndex = index;
        }
    }

    private void setOnListener() {

    }

    private int keyBackClickCount = 0;
    private TitleColorSegmentView sv_title;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            switch (keyBackClickCount++) {
                case 0:
                    Toast.makeText(this, "再次按返回键退出", Toast.LENGTH_SHORT).show();
                    Timer timer = new Timer();
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            keyBackClickCount = 0;
                        }
                    }, 2000);
                    break;
                case 1:
                    finish();
                    overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);
                    break;
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

    }

    private OnSegmentSelectedListener listener = new OnSegmentSelectedListener() {

        @Override
        public void onSegmentSelected(boolean isUnlockSelected) {
            if (isUnlockSelected) {
                FragmentTransaction trx = getSupportFragmentManager()
                        .beginTransaction();
                trx.hide(addressListFragment).show(msgfragment).commit();
                index = 0;
                currentTabIndex = index;
                Log.e("test", "index =0");
            } else {
                FragmentTransaction trx = getSupportFragmentManager()
                        .beginTransaction();
                trx.hide(msgfragment).show(addressListFragment).commit();
                index = 4;
                currentTabIndex = index;
                Log.e("test", "index =4");
            }
        }
    };

    private void initIm() {
        /**
         * 设置会话界面操作的监听器。
         */
        connect(SPUtil.getString(MainActivity.this, "token2", ""));

        RongIM.setConversationBehaviorListener(new MyConversationBehaviorListener());
        RongIM.setConversationListBehaviorListener(new MyConversationListBehaviorListener());
        RongIMClient
                .setConnectionStatusListener(new MyConnectionStatusListener());

        RongIM.setLocationProvider(new LocationProvider() {

            @Override
            public void onStartLocation(Context arg0, LocationCallback arg1) {
                DemoContext.getInstance().setLastLocationCallback(arg1);
                // Log.e("test", "onStartLocation");
                Intent intent = new Intent(MainActivity.this,
                        SOSOLocationActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });

        // 扩展功能自定义
        InputProvider.ExtendProvider[] provider = {
                new PhotoInputProvider(RongContext.getInstance()),// 图片
                new CameraInputProvider(RongContext.getInstance()),// 相机
                new LocationInputProvider(RongContext.getInstance()),// 地理位置
        };
        RongIM.resetInputExtensionProvider(
                Conversation.ConversationType.PRIVATE, provider);
        RongIM.resetInputExtensionProvider(
                Conversation.ConversationType.DISCUSSION, provider);
        RongIM.resetInputExtensionProvider(Conversation.ConversationType.GROUP,
                provider);
        RongIM.resetInputExtensionProvider(
                Conversation.ConversationType.CUSTOMER_SERVICE, provider);

    }

    private class MyConversationListBehaviorListener implements
            RongIM.ConversationListBehaviorListener {

        @Override
        public boolean onConversationClick(Context arg0, View arg1,
                                           UIConversation arg2) {
            Log.e("test", "MyConversationListBehaviorListener");
            // String onUserPortraitClickid =
            // getIntent().getData().getQueryParameter("targetId");

            return false;

        }

        @Override
        public boolean onConversationLongClick(Context arg0, View arg1,
                                               UIConversation arg2) {
            // TODO Auto-generated method stub
            return false;
        }

        @Override
        public boolean onConversationPortraitClick(Context arg0,
                                                   ConversationType arg1, String arg2) {
            // TODO Auto-generated method stub
            return false;
        }

        @Override
        public boolean onConversationPortraitLongClick(Context arg0,
                                                       ConversationType arg1, String arg2) {
            // TODO Auto-generated method stub
            return false;
        }
    }

    private class MyConversationBehaviorListener implements
            RongIM.ConversationBehaviorListener {

        /**
         * 当点击用户头像后执行。
         *
         * @param context          上下文。
         * @param conversationType 会话类型。
         * @param userInfo         被点击的用户的信息。
         * @return 如果用户自己处理了点击后的逻辑，则返回 true，否则返回 false，false 走融云默认处理方式。
         */
        @Override
        public boolean onUserPortraitClick(Context context,
                                           Conversation.ConversationType conversationType,
                                           UserInfo userInfo) {

            // Intent intent = new
            // Intent(JpjMainActivity.this,MineConversationInfo.class);
            // intent.putExtra("userInfo", userInfo.getUserId());
            // SPUtils.put(context, "onUserPortraitClickid",
            // userInfo.getUserId());
            // // Toast.makeText(MainActivity.this, userInfo.getName(),
            // 0).show();
            // startActivity(intent);

            // Log.e("testtime", ""+userInfo.getPortraitUri());

            return true;
        }

        /**
         * 当长按用户头像后执行。
         *
         * @param context          上下文。
         * @param conversationType 会话类型。
         * @param userInfo         被点击的用户的信息。
         * @return 如果用户自己处理了点击后的逻辑，则返回 true，否则返回 false，false 走融云默认处理方式。
         */
        @Override
        public boolean onUserPortraitLongClick(Context context,
                                               Conversation.ConversationType conversationType,
                                               UserInfo userInfo) {
            // listurl = new ArrayList<String>();
            // listurl.add(""+userInfo.getPortraitUri());//"http://t2.qlogo.cn/mbloghead/1669d711fcd8498988dc/180.jpg"
            // Intent intent3 = new Intent(JpjMainActivity.this,
            // GetPicShowActivity.class);
            // intent3.putStringArrayListExtra("urllist", listurl);
            // intent3.putExtra("position",0);
            // startActivity(intent3);

            return true;
        }

        /**
         * 当点击消息时执行。
         *
         * @param context 上下文。
         * @param view    触发点击的 View。
         * @param message 被点击的消息的实体信息。
         * @return 如果用户自己处理了点击后的逻辑，则返回 true， 否则返回 false, false 走融云默认处理方式。
         */
        @Override
        public boolean onMessageClick(Context context, View view,
                                      Message message) {

            // Log.e("test", "onMessageClick   click");
            if (message.getContent() instanceof ImageMessage) {
                Intent intent = new Intent(MainActivity.this,
                        PhotoActivity.class);
                intent.putExtra("message", message);
                startActivity(intent);
                return true;
            }
            if (message.getContent() instanceof LocationMessage) {
                Intent intent = new Intent(context, SOSOLocationActivity.class);
                intent.putExtra("location", message.getContent());
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
                return true;
            }

            return false;
        }

        /**
         * 当长按消息时执行。
         *
         * @param context 上下文。
         * @param view    触发点击的 View。
         * @param message 被长按的消息的实体信息。
         * @return 如果用户自己处理了长按后的逻辑，则返回 true，否则返回 false，false 走融云默认处理方式。
         */
        @Override
        public boolean onMessageLongClick(Context context, View view,
                                          Message message) {
            return false;
        }

        /**
         * 当点击链接消息时执行。
         *
         * @param context 上下文。
         * @param link    被点击的链接。
         * @return 如果用户自己处理了点击后的逻辑处理，则返回 true， 否则返回 false, false 走融云默认处理方式。
         */
        @Override
        public boolean onMessageLinkClick(Context context, String link) {
            return false;
        }

    }

    private class MyConnectionStatusListener implements
            RongIMClient.ConnectionStatusListener {

        @Override
        public void onChanged(ConnectionStatus connectionStatus) {

            switch (connectionStatus) {

                case CONNECTED:// 连接成功。
                    Log.e("testlogin", "连接成功");
                    break;
                case DISCONNECTED:// 断开连接。
                    Log.e("testlogin", "断开连接");
                    break;
                case CONNECTING:// 连接中。
                    Log.e("testlogin", "连接中");
                    break;
                case NETWORK_UNAVAILABLE:// 网络不可用。
                    Log.e("testlogin", "网络不可用");
                    break;
                case KICKED_OFFLINE_BY_OTHER_CLIENT:// 用户账户在其他设备登录，本机会被踢掉线
                    Log.e("testlogin", "用户账户在其他设备登录，本机会被踢掉线");
                    Looper.prepare();
                    NormalDialogCustomAttr();
                    Looper.loop();
                    break;
            }
        }
    }

    /**
     * 建立与融云服务器的连接
     *
     * @param token
     */
    private void connect(String token) {

        // if
        // (getApplicationInfo().packageName.equals(App.getCurProcessName(getApplicationContext())))
        // {

        /**
         * IMKit SDK调用第二步,建立与服务器的连接
         */
        RongIM.connect(token, new RongIMClient.ConnectCallback() {

            /**
             * Token 错误，在线上环境下主要是因为 Token 已经过期，您需要向 App Server 重新请求一个新的 Token
             */
            @Override
            public void onTokenIncorrect() {
                // Toast.makeText(MainActivity.this, "服务器连接异常", 0).show();
                Log.d("LoginActivity", "--onTokenIncorrect");
                reconnect(SPUtil.getString(MainActivity.this, "token2", ""));
            }

            /**
             * 连接融云成功
             *
             * @param userid
             *            当前 token
             */
            @Override
            public void onSuccess(final String userid) {
                // Toast.makeText(MainActivity.this, "121", 0).show();
                Log.d("LoginActivity", "--onSuccess" + userid);
                // startActivity(new Intent(LoginActivity.this,
                // MainActivity.class));
                // finish();

                final Conversation.ConversationType[] conversationTypes = {
                        Conversation.ConversationType.PRIVATE,
                        Conversation.ConversationType.DISCUSSION,
                        Conversation.ConversationType.GROUP,
                        Conversation.ConversationType.SYSTEM,
                        Conversation.ConversationType.PUBLIC_SERVICE,
                        Conversation.ConversationType.APP_PUBLIC_SERVICE};
                RongIM.getInstance().setOnReceiveUnreadCountChangedListener(
                        mCountListener, conversationTypes);
                // RongIM.getInstance().setOnReceiveUnreadCountChangedListener(mCountListener1,
                // Conversation.ConversationType.APP_PUBLIC_SERVICE);

                // RongIM.setUserInfoProvider(new UserInfoProvider() {
                //
                // @Override
                // public UserInfo getUserInfo(String arg0) {
                //
                // String username = SPUtil.getString(MainActivity.this,
                // "name", "");
                // String userheadimg = SPUtil.getString(
                // MainActivity.this, "icon", "");
                // if (userid.equals(arg0)) {
                //
                // return new UserInfo(arg0, username, Uri
                // .parse(userheadimg));
                // }
                // return null;
                // }
                // }, true);

            }

            /**
             * 连接融云失败
             *
             * @param errorCode
             *            错误码，可到官网 查看错误码对应的注释
             */
            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {
                // Toast.makeText(MainActivity.this, "131", 0).show();
                // Log.d("LoginActivity", "--onError" + errorCode);
            }
        });
    }

    /**
     * 重连
     *
     * @param token
     */
    @SuppressLint("NewApi")
    private void reconnect(String token) {

        if (MainActivity.this.getApplicationInfo().packageName.equals(App
                .getCurProcessName(MainActivity.this.getApplicationContext()))) {

            RongIM.connect(token, new RongIMClient.ConnectCallback() {
                @Override
                public void onTokenIncorrect() {

                }

                @Override
                public void onSuccess(String s) {

                    // enterFragment();
                }

                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {

                }
            });
        }
    }

    public RongIM.OnReceiveUnreadCountChangedListener mCountListener = new RongIM.OnReceiveUnreadCountChangedListener() {
        @Override
        public void onMessageIncreased(int count) {
            if (count == 0) {
                mUnreadNumView.setVisibility(View.GONE);
            } else if (count > 0 && count < 100) {
                mUnreadNumView.setVisibility(View.VISIBLE);
                mUnreadNumView.setText(count + "");
            } else {
                mUnreadNumView.setVisibility(View.VISIBLE);
                mUnreadNumView.setText(R.string.no_read_message);
            }
        }
    };

    private BaseAnimatorSet bas_in;
    private BaseAnimatorSet bas_out;

    public void setBasIn(BaseAnimatorSet bas_in) {
        this.bas_in = bas_in;
    }

    public void setBasOut(BaseAnimatorSet bas_out) {
        this.bas_out = bas_out;
    }

    private void NormalDialogCustomAttr() {

        final NormalDialog dialog = new NormalDialog(getApplicationContext());
        dialog.content("用户账户在其他设备登录")//
                .style(NormalDialog.STYLE_TWO)//
                .titleTextSize(23)//
                .showAnim(bas_in)//
                .dismissAnim(bas_out)//
                .show();
        dialog.setCanceledOnTouchOutside(false);
        dialog.btnText("取消", "重新登录");
        dialog.setOnBtnLeftClickL(new OnBtnLeftClickL() {

            @Override
            public void onBtnLeftClick() {
                // TODO Auto-generated method stub

                dialog.dismiss();
                System.exit(0);
            }
        });
        dialog.setOnBtnRightClickL(new OnBtnRightClickL() {

            @Override
            public void onBtnRightClick() {

                SPUtils.put(getApplicationContext(), "Friendlistjson", "");
                SPUtil.putString(getApplicationContext(), "account", "");
                SPUtil.putString(getApplicationContext(), "token1", "");
                SPUtil.putString(getApplicationContext(), "token2", "");
                SPUtil.putString(getApplicationContext(), "name", "");
                SPUtil.putString(getApplicationContext(), "icon", "");
                SPUtil.putString(getApplicationContext(), "role", role);
                SPUtil.putString(getApplicationContext(),
                        ConfigConstant.USERNAME, "");
                SPUtils.put(getApplicationContext(),
                        ConfigConstant.IS_LOGIN_ON, false);
                SPUtils.put(getApplicationContext(), ConfigConstant.USERTOKEN,
                        "");

                RongIM.getInstance().logout();
                Intent intent = new Intent(MainActivity.this,
                        StartActivity.class);
                startActivity(intent);
                MainActivity.this.finish();
            }
        });
    }
}
